package light.head.dao.inv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvAccount;
@Service
public class InvAccountDAO extends BaseDAO<InvAccount, Integer>{
	public RESULT findByMap(Integer oc, Map<String,String> map, PageBean pb) {
		if (oc == null ) return null;
		
		StringBuffer hql = new StringBuffer("FROM InvAccount ia WHERE ia.oc = ?");
		List<Object> list = new ArrayList<Object>();
		
		list.add(oc);
		if (null != map) {
			String card = map.get(Parm.CARD);
			String cn = map.get(Parm.CN);
			String on = map.get(Parm.ON);
			String time1 = map.get(Parm.TIME1);
			String time2 = map.get(Parm.TIME2);
			String deleted = map.get(Parm.DELETED);
			
			if (isNotNull(card)) {
				list.add("%" + card + "%");
				hql.append(" AND ia.card LIKE ?");
			}if (isNotNull(cn)) {
				list.add("%" + cn + "%");
				hql.append(" AND ia.cu IN (SELECT ui.code FROM UserInfo ui WHERE ui.realName LIKE ?)");
			}if (isNotNull(on)) {
				list.add("%" + on + "%");
				hql.append(" AND ia.oc IN (SELECT o.code FROM Organ o WHERE o.name LIKE ?)");
			}if (isNotNull(time1)) {
				list.add(DateUtils.getDateByStr(time1, null));
				hql.append(" AND ia.ct >= ?");
			}
			if (isNotNull(time2)) {
				list.add(DateUtils.getDateByStr(time2, null));
				hql.append(" AND ia.ct <= ?");
			}
			if (isNotNull(deleted)) {
				list.add(Boolean.parseBoolean(deleted));
				hql.append(" AND ia.deleted = ?");
			}
		}
		hql.append(" ORDER BY ia.code DESC");
		return findToPageBean(hql.toString(), pb, list);
	}
	
	public List<InvAccount> findByNameOc(String name, Integer oc){
		if (name == null || oc == null) return null;
		StringBuffer hql = new StringBuffer("FROM InvAccount ia WHERE ia.name = ? AND ia.oc = ? ");
		List<Object> parm = new ArrayList<Object>();
		
		parm.add(name);
		parm.add(oc);
		
		return find(hql.toString(), parm.toArray());
	}
	
	public RESULT update(InvAccount ia) {
		if (null == ia || ia.getCode() == null) return null;
		InvAccount db = this.get(ia.getCode());
		if (null == db) return RESULT.NOT_FIND;
		
		boolean ok = false;
		if (!isNotNull(db.getAtn()) && isNotNull(ia.getAtn()) || (!db.getAtn().equals(ia.getAtn()))) {
			db.setAtn(ia.getAtn());
			ok = true;
		}if (db.getAtc() == null && ia.getAtc() != null || db.getAtc().intValue() != ia.getAtc().intValue()) {
			db.setAtc(ia.getAtc());
			ok = true;
		}
		if (!isNotNull(db.getCard()) && isNotNull(ia.getCard()) || (!db.getCard().equals(ia.getCard()))) {
			db.setCard(ia.getCard());
			ok = true;
		}
		if (ok)
			return super.upd(db);
		
		return RESULT.SUCCESS;
	}
}
